package main

import (
	"bufio"
	"bytes"
	"embed"
	"fmt"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"apiote.xyz/p/go-dirty"
	"github.com/bytesparadise/libasciidoc"
	"github.com/bytesparadise/libasciidoc/pkg/configuration"
	"golang.org/x/text/language"
)

//go:embed static
var staticFS embed.FS

//go:embed programs
var programsFS embed.FS

//go:embed templates
var templatesFS embed.FS

type Nil struct {
	Adr string
}

type PGP struct {
	Key string
	Adr string
}

type Redirection struct {
	ID  string
	URL string
	Adr string
}

type Version struct {
	Description string
	Module      string
	Content     template.HTML
}

type Programs struct {
	Programs map[string]Program
	Adr      string
}

type Program struct {
	Name           string
	Tldr           string
	DefaultVersion string
	Source         string
	Versions       map[string]Version
	Tag            string
	Module         string
	Content        template.HTML
}

type Holiday struct {
	Name  string
	Month int
	Day   int
	Rrule string
	Year  int
}

func (h Holiday) Format() string {
	var result string
	if h.Year > 0 {
		result = strconv.FormatInt(int64(h.Year), 10)
	} else {
		result = "2001"
	}
	if h.Month < 10 {
		result += "0"
	}
	result += strconv.FormatInt(int64(h.Month), 10)
	if h.Day < 10 {
		result += "0"
	}
	result += strconv.FormatInt(int64(h.Day), 10)

	return result
}

func (h Holiday) UID() string {
	uid := strings.ReplaceAll(h.Name, " ", "")
	uid = strings.ReplaceAll(uid, "’", "")
	uid = strings.ReplaceAll(uid, ".", "")
	uid = strings.ToLower(uid)
	if h.Year != 0 {
		uid = uid + "_" + strconv.FormatInt(int64(h.Year), 10)
	}
	return uid + "@apiote.xyz"
}

func chooseLanguage(name, acceptLanguage string) string {
	languagesSet := map[language.Tag]struct{}{}
	entries, err := templatesFS.ReadDir("templates")
	for _, entry := range entries {
		if entry.IsDir() {
			continue
		}

		nameParts := strings.Split(entry.Name(), ".")
		if len(nameParts) == 2 {
			continue
		}

		l, err := language.Parse(nameParts[1])
		if err != nil {
			continue
		}
		languagesSet[l] = struct{}{}
	}

	if len(languagesSet) == 0 {
		return name
	}

	acceptLanguages, _, err := language.ParseAcceptLanguage(acceptLanguage)
	if err != nil {
		return name
	}

	languages := make([]language.Tag, len(languagesSet)+1)
	languages[0] = language.English
	i := 1
	for l := range languagesSet {
		languages[i] = l
		i++
	}

	matcher := language.NewMatcher(languages)
	tag, _, _ := matcher.Match(acceptLanguages...)
	lang, _ := tag.Base()

	return name + "." + lang.String()
}

func showHtml(w http.ResponseWriter, name string, data any, acceptLanguage string) {
	name = chooseLanguage(name, acceptLanguage)
	t, err := template.ParseFS(templatesFS, "templates/"+name+".html", "templates/aside.html", "templates/header.html", "templates/nav.html", "templates/head.html", "templates/head_program.html")
	if err != nil {
		log.Println(err)
		if os.IsNotExist(err) {
			renderStatus(w, http.StatusNotImplemented, acceptLanguage)
			return
		}
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprint(w, "Error 500")
		return
	}
	err = t.Execute(w, data)
	if err != nil {
		log.Println(err)
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprint(w, "Error 500")
		return
	}
}

func renderStatus(w http.ResponseWriter, status int, acceptLanguage string) {
	w.WriteHeader(status)
	showHtml(w, fmt.Sprint(status), nil, acceptLanguage)
}

func index(w http.ResponseWriter, r *http.Request) {
	acceptLanguage := r.Header.Get("Accept-Language")
	path := strings.Split(r.URL.Path[1:], "/")
	if path[0] == "" {
		showHtml(w, "index", nil, acceptLanguage)
	}
	if path[0] != "" {
		renderStatus(w, http.StatusNotFound, acceptLanguage)
	}
}

func donate(w http.ResponseWriter, r *http.Request) {
	acceptLanguage := r.Header.Get("Accept-Language")
	showHtml(w, "donate", nil, acceptLanguage)
}

func readPrograms() (map[string]Program, error) {
	m := map[string]Program{}
	programs := []Program{}
	file, err := programsFS.Open("programs/index.dirty")
	if err != nil {
		log.Println(err)
		return m, err
	}
	defer file.Close()
	err = dirty.LoadStruct(file, &programs)
	if err != nil {
		log.Println(err)
		log.Println(programs)
	}
	for _, program := range programs {
		m[program.Name] = program
	}
	return m, err
}

func programs(w http.ResponseWriter, r *http.Request) {
	acceptLanguage := r.Header.Get("Accept-Language")
	path := strings.Split(r.URL.Path[1:], "/")
	programs, err := readPrograms()
	if err != nil {
		renderStatus(w, http.StatusInternalServerError, acceptLanguage)
		return
	}
	var (
		program Program
		version Version
		present bool
	)
	if path[1] == "" {
		showHtml(w, "programs", Programs{programs, "https://apiote.xyz/programs/"}, acceptLanguage)
		return
	} else if len(path) == 2 {
		name := path[1]
		program = programs[name]
		version, present = program.Versions[""]
	} else if len(path) == 3 {
		name := path[1]
		program = programs[name]
		version, present = program.Versions[path[2]]
	} else {
		renderStatus(w, http.StatusNotFound, acceptLanguage)
		return
	}
	if !present {
		renderStatus(w, http.StatusNotFound, acceptLanguage)
		return
	}
	file, err := programsFS.Open("programs/" + version.Description)
	if err != nil {
		if os.IsNotExist(err) {
			renderStatus(w, http.StatusNotFound, acceptLanguage)
			return
		} else {
			log.Println(err)
		}
		return
	}
	defer file.Close()
	content, err := io.ReadAll(file)
	if err != nil {
		log.Println(err)
		return
	}
	if len(path) > 2 {
		program.Tag = path[2]
	} else {
		program.Tag = ""
	}
	program.Module = version.Module

	reader := strings.NewReader(string(content))
	writer := bytes.NewBuffer([]byte{})
	config := configuration.NewConfiguration()
	libasciidoc.Convert(reader, writer, config)
	program.Content = template.HTML(writer.Bytes())

	showHtml(w, "program", program, acceptLanguage)
}

func blogEntries(w http.ResponseWriter, r *http.Request) {
}

func pgp(w http.ResponseWriter, r *http.Request) {
	acceptLanguage := r.Header.Get("Accept-Language")
	accept := r.Header["Accept"][0]
	path := strings.Split(r.URL.Path[1:], "/")
	if path[1] == "" {
		renderStatus(w, http.StatusNotFound, acceptLanguage)
	} else {
		file, err := staticFS.Open("static/" + path[1] + ".asc")
		defer file.Close()
		if err != nil && os.IsNotExist(err) {
			renderStatus(w, http.StatusNotFound, acceptLanguage)
			return
		} else if err != nil {
			log.Println(err)
			renderStatus(w, http.StatusInternalServerError, acceptLanguage)
			return
		}
		key, err := ioutil.ReadAll(file)
		if err != nil {
			log.Println(err)
			renderStatus(w, http.StatusInternalServerError, acceptLanguage)
			return
		}
		w.Header().Set("Vary", "Accept")
		if strings.Contains(accept, "text/html") {
			showHtml(w, "pgp", PGP{string(key), "https://apiote.xyz/pgp/me"}, acceptLanguage)
		} else {
			w.Header().Set("Content-Type", "application/pgp-key")
			fmt.Fprintf(w, "%s", key)
		}
	}
}

func easter(y int) []Holiday {
	a := y % 19
	b := y % 4
	c := y % 7
	p := y / 100
	q := (13 + (8 * p)) / 25
	m := (15 - q + p - (p / 4)) % 30
	n := (4 + p - (p / 4)) % 7
	d := (19*a + m) % 30
	e := (n + (2 * b) + (4 * c) + (6 * d)) % 7

	var easterDate time.Time
	if d == 29 && e == 6 {
		easterDate = time.Date(y, 4, 19, 0, 0, 0, 0, time.Local)
	} else if d == 28 && e == 6 {
		easterDate = time.Date(y, 4, 18, 0, 0, 0, 0, time.Local)
	} else {
		easterDate = time.Date(y, 3, 22, 0, 0, 0, 0, time.Local).AddDate(0, 0, d+e)
	}

	holidays := []Holiday{}
	holidays = append(holidays, Holiday{
		Name:  "Easter",
		Month: int(easterDate.Month()),
		Day:   easterDate.Day(),
		Year:  y,
	})
	h := easterDate.AddDate(0, 0, -52)
	holidays = append(holidays, Holiday{
		Name:  "Fat Thursday",
		Month: int(h.Month()),
		Day:   h.Day(),
		Year:  y,
	})
	h = easterDate.AddDate(0, 0, -47)
	holidays = append(holidays, Holiday{
		Name:  "Shrove Tuesday",
		Month: int(h.Month()),
		Day:   h.Day(),
		Year:  y,
	})
	h = easterDate.AddDate(0, 0, -46)
	holidays = append(holidays, Holiday{
		Name:  "Ash Wednesday",
		Month: int(h.Month()),
		Day:   h.Day(),
		Year:  y,
	})
	h = easterDate.AddDate(0, 0, -7)
	holidays = append(holidays, Holiday{
		Name:  "Palm Sunday",
		Month: int(h.Month()),
		Day:   h.Day(),
		Year:  y,
	})
	h = easterDate.AddDate(0, 0, -3)
	holidays = append(holidays, Holiday{
		Name:  "Maundy Thursday",
		Month: int(h.Month()),
		Day:   h.Day(),
		Year:  y,
	})
	h = easterDate.AddDate(0, 0, -2)
	holidays = append(holidays, Holiday{
		Name:  "Good Friday",
		Month: int(h.Month()),
		Day:   h.Day(),
		Year:  y,
	})
	h = easterDate.AddDate(0, 0, -1)
	holidays = append(holidays, Holiday{
		Name:  "Easter Eve",
		Month: int(h.Month()),
		Day:   h.Day(),
		Year:  y,
	})
	h = easterDate.AddDate(0, 0, 1)
	holidays = append(holidays, Holiday{
		Name:  "Easter Monday",
		Month: int(h.Month()),
		Day:   h.Day(),
		Year:  y,
	})
	h = easterDate.AddDate(0, 0, 49)
	holidays = append(holidays, Holiday{
		Name:  "Pentecost",
		Month: int(h.Month()),
		Day:   h.Day(),
		Year:  y,
	})
	h = easterDate.AddDate(0, 0, 60)
	holidays = append(holidays, Holiday{
		Name:  "Corpus Christi",
		Month: int(h.Month()),
		Day:   h.Day(),
		Year:  y,
	})

	return holidays
}

func calendar(dataDir string) func(w http.ResponseWriter, r *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		acceptLanguage := r.Header.Get("Accept-Language")
		file, err := os.Open(filepath.Join(dataDir, "holidays.dirty"))
		if err != nil {
			if os.IsNotExist(err) {
				renderStatus(w, http.StatusNotFound, acceptLanguage)
				return
			} else {
				log.Println(err)
				renderStatus(w, http.StatusInternalServerError, acceptLanguage)
				return
			}
		}
		defer file.Close()
		holidays := []Holiday{}
		err = dirty.LoadStruct(file, &holidays)
		if err != nil {
			log.Println(err)
			log.Println(holidays)
			renderStatus(w, http.StatusInternalServerError, acceptLanguage)
			return
		}
		t, err := template.ParseFS(templatesFS, "templates/calendar.ics")
		if err != nil {
			log.Println(err)
			if os.IsNotExist(err) {
				renderStatus(w, http.StatusNotImplemented, acceptLanguage)
				return
			}
			renderStatus(w, http.StatusInternalServerError, acceptLanguage)
			return
		}
		thisYear := time.Now().Year()
		for i := 0; i < 10; i++ {
			holidays = append(holidays, easter(thisYear+i)...)
		}
		w.Header().Set("Content-Type", "text/calendar")
		err = t.Execute(w, holidays)
		if err != nil {
			log.Println(err)
			renderStatus(w, http.StatusInternalServerError, acceptLanguage)
			return
		}
	}
}

func shortRedirect(dataDir, stateDir string) func(w http.ResponseWriter, r *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		acceptLanguage := r.Header.Get("Accept-Language")
		path := strings.Split(r.URL.Path[1:], "/")
		if len(path) == 2 && path[1] == "" {
			if r.Method == "" || r.Method == "GET" {
				showHtml(w, "s", Nil{"https://apiote.xyz/s/"}, acceptLanguage)
			} else if r.Method == "POST" {
				r.ParseForm()
				id := r.PostForm.Get("id")
				url := r.PostForm.Get("url")
				password := r.PostForm.Get("password")
				if id == "" {
					var letters = []rune("3478ABCDEFHJKMNRTWXY")
					b := make([]rune, 6)
					for i := range b {
						b[i] = letters[rand.Intn(len(letters))]
					}
					id = string(b)
				} else {
					id = strings.ToUpper(id)
				}
				if url == "" {
					renderStatus(w, http.StatusBadRequest, acceptLanguage)
					return
				}
				hash, err := ioutil.ReadFile(filepath.Join(stateDir, "password"))
				if err != nil {
					log.Println(err)
					renderStatus(w, http.StatusInternalServerError, acceptLanguage)
					return
				}
				passMatch, err := ComparePasswordAndHash(password, string(hash))
				if err != nil {
					log.Println(err)
					renderStatus(w, http.StatusInternalServerError, acceptLanguage)
					return
				}
				if !passMatch {
					renderStatus(w, http.StatusForbidden, acceptLanguage)
					return
				}

				file, err := os.OpenFile(filepath.Join(stateDir, "s.toml"), os.O_RDONLY|os.O_CREATE, 0600)
				if err != nil {
					log.Println(err)
					renderStatus(w, http.StatusInternalServerError, acceptLanguage)
					return
				}
				defer file.Close()

				shorts := map[string]string{}
				scanner := bufio.NewScanner(file)
				for scanner.Scan() {
					line := strings.Split(scanner.Text(), " = ")
					shorts[line[0]] = line[1]
				}
				if err := scanner.Err(); err != nil {
					log.Println(err)
					renderStatus(w, http.StatusInternalServerError, acceptLanguage)
					return
				}
				file.Close()

				if _, ok := shorts[id]; ok {
					renderStatus(w, http.StatusConflict, acceptLanguage)
					return
				}
				shorts[id] = url

				file, err = os.OpenFile(filepath.Join(stateDir, "s.toml"), os.O_WRONLY|os.O_TRUNC, 0600)
				if err != nil {
					log.Println(err)
					renderStatus(w, http.StatusInternalServerError, acceptLanguage)
					return
				}
				defer file.Close()
				for shortID, shortURL := range shorts {
					_, err = file.WriteString(shortID + " = " + shortURL + "\n")
					if err != nil {
						log.Println(err)
						renderStatus(w, http.StatusInternalServerError, acceptLanguage)
						return
					}
				}

				w.Header().Add("X-Redirection", "https://apiote.xyz/s/"+id)
				w.WriteHeader(http.StatusCreated)
				showHtml(w, "s201", Redirection{id, url, "https://apiote.xyz/s/" + id}, acceptLanguage)
			}
		} else if len(path) != 2 {
			renderStatus(w, http.StatusNotFound, acceptLanguage)
		} else {
			id := strings.ToUpper(path[1])
			file, err := os.Open(filepath.Join(stateDir, "s.toml"))
			if err != nil {
				log.Println(err)
				renderStatus(w, http.StatusInternalServerError, acceptLanguage)
				return
			}
			defer file.Close()

			scanner := bufio.NewScanner(file)
			for scanner.Scan() {
				line := strings.Split(scanner.Text(), " = ")
				if len(line) < 2 {
					continue
				}
				if line[0] == id {
					http.Redirect(w, r, line[1], http.StatusMovedPermanently)
					return
				}
			}
			renderStatus(w, http.StatusNotFound, acceptLanguage)
		}
	}
}

func shortShow(stateDir string) func(w http.ResponseWriter, r *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		acceptLanguage := r.Header.Get("Accept-Language")
		path := strings.Split(r.URL.Path[1:], "/")
		if len(path) == 2 && path[1] != "" {
			id := strings.ToUpper(path[1])
			file, err := os.Open(filepath.Join(stateDir, "s.toml"))
			if err != nil {
				log.Println(err)
				renderStatus(w, http.StatusInternalServerError, acceptLanguage)
				return
			}
			defer file.Close()

			scanner := bufio.NewScanner(file)
			for scanner.Scan() {
				line := strings.Split(scanner.Text(), " = ")
				if len(line) < 2 {
					continue
				}
				if line[0] == id {
					showHtml(w, "short", Redirection{line[0], line[1], "https://apiote.xyz/short/" + line[0]}, acceptLanguage)
					return
				}
			}
			renderStatus(w, http.StatusNotFound, acceptLanguage)
		} else {
			renderStatus(w, http.StatusNotFound, acceptLanguage)
		}
	}
}

func wkd(w http.ResponseWriter, r *http.Request) {
	acceptLanguage := r.Header.Get("Accept-Language")
	path := strings.Split(r.URL.Path[1:], "/")
	if path[3] == "" {
		renderStatus(w, http.StatusNotFound, acceptLanguage)
	} else {
		file, err := staticFS.Open("static/" + path[3] + ".pgp")
		defer file.Close()
		if err != nil && os.IsNotExist(err) {
			renderStatus(w, http.StatusNotFound, acceptLanguage)
			return
		} else if err != nil {
			log.Println(err)
			renderStatus(w, http.StatusInternalServerError, acceptLanguage)
			return
		}
		w.Header().Set("Content-Type", "application/pgp-key")
		w.Header().Set("Access-Control-Allow-Origin", "*")
		_, err = io.Copy(w, file)
		if err != nil {
			log.Println(err)
			renderStatus(w, http.StatusInternalServerError, acceptLanguage)
		}
	}
}

func dogtag(w http.ResponseWriter, r *http.Request) {
	acceptLanguage := r.Header.Get("Accept-Language")
	showHtml(w, "dogtag", Nil{"https://apiote.xyz/tag"}, acceptLanguage)
}

func route(dataDir, stateDir string) {
	http.HandleFunc("/", index)

	http.Handle("/static/", http.FileServer(http.FS(staticFS)))

	http.HandleFunc("/b/", blogEntries)
	http.HandleFunc("/blog/", blogEntries)
	http.HandleFunc("/p/", programs)
	http.HandleFunc("/programs/", programs)
	http.HandleFunc("/donate", donate)
	http.HandleFunc("/pgp/", pgp)
	http.HandleFunc("/calendar", calendar(dataDir))
	http.HandleFunc("/tag", dogtag)

	http.HandleFunc("/s/", shortRedirect(dataDir, stateDir))
	http.HandleFunc("/short/", shortShow(stateDir))

	http.HandleFunc("/.well-known/openpgpkey/hu/", wkd)

	e := http.ListenAndServe("127.0.0.1:8080", nil)
	if e != nil {
		log.Println(e)
	}
}
